package com.ljw.spring.annotation.selector;

import com.ljw.spring.annotation.bean.Desk;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @FileName MyImportBeanDefinitionRegistrar
 * @Description TODO @Import(value = {Color.class, Car.class, MyImportSelector.class,MyImportBeanDefinitionRegistrar.class})
 *                  向IOC容器手动注册指定组件：registry.registerBeanDefinition("desk",definition);
 * @Author ljw
 * @Date 2021/2/2 0:12
 * @Version 1.0
 */
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    /**
     *
     * @param importingClassMetadata 当前标注@Import注解的类的 所有注解（包括@Import注解）信息
     * @param registry 接口BeanDefinitionRegistry，手动注册bean：
     *                 调用方法BeanDefinitionRegistry.registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
     */
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        //判断IOC容器中是否有组件名为user的组件
        boolean user = registry.containsBeanDefinition("user");
        if (user){
            //指定要注册的类
            RootBeanDefinition definition = new RootBeanDefinition(Desk.class);
            //手动向IOC容器加入指定组件
            registry.registerBeanDefinition("desk",definition);
            System.out.println("向IOC容器手动注册指定组件:"+definition.getBeanClassName());
        }
    }
}
